import mongoose from 'mongoose';
import utils from '../utils';
import { isEmail, isPhone, user } from '../config';
export interface IUser extends mongoose.Document {
  email: string;
  phone: string;
  password: string;
  nickname: string;
  name: string;
  gender: string;
  birthday: string;
  address: string;
  job: string;
  edu: string;
  salary: string;
  sign: string;
}

export const model = {
  email: String,
  phone: String,
  password: String,
  nickname: String,
  name: String,
  gender: String,
  birthday: String,
  address: String,
  job: String,
  edu: String,
  salary: String,
  sign: String,
};

export const Schema = new mongoose.Schema(model);

const m: any = mongoose.model<IUser>('User', Schema);

m.findByEmail = async function(email: string) {
  const res = await m.findOne({ email });
  return res;
};

m.findByPhone = async function(phone: string) {
  const res = await m.findOne({ phone });
  return res;
};

m.findByUsername = async function(username: string) {
  const email = await m.findByEmail(username);
  const phone = await m.findByPhone(username);
  return email || phone;
};

m.hasEmail = async function(email: string) {
  const res = await m.findByEmail(email);
  let ret = true;
  if (!res) {
    ret = false;
  }
  return ret;
};

m.hasPhone = async function(phone: string) {
  const res = await m.findByPhone(phone);
  let ret = true;
  if (!res) {
    ret = false;
  }
  return ret;
};

// m.addUser = async function() {
//   const res = await m.create({ children: [{ name: 'Luke' }] });
// };

m.validatePassword = async function(username: string, password: string, type: number) {
  let ret = false;

  if (type === isEmail) {
    const res = await m.findByEmail(username);

    ret = res.password == password;
  }
  if (type === isPhone) {
    const res = await m.findByPhone(username);
    ret = res.password == password;
  }
  return ret;
};

export default m;
